package com.example.spider.proxy;

import com.example.spider.proxy.core.ProxyInfo;
import com.example.spider.task.Task;

/**
 * 存储当前爬虫下载器的上下文信息
 */
public class SpiderContextHolder {

    private static final ThreadLocal<Task<?>> taskLocal = new ThreadLocal<>();

    private static final ThreadLocal<ProxyInfo> proxyInfoLocal = ThreadLocal.withInitial(() ->
            ProxyPool.NO_PROXY
    );

    public static void setProxyInfo(ProxyInfo proxyInfo) {
        proxyInfoLocal.set(proxyInfo);
    }

    public static ProxyInfo getProxyInfo() {
        ProxyInfo proxyInfo = proxyInfoLocal.get();
        return proxyInfo == null ? ProxyPool.NO_PROXY : proxyInfo;
    }

    public static Task<?> getTask() {
        return taskLocal.get();
    }

    public static void setTask(Task<?> charset) {
        taskLocal.set(charset);
    }

    public static void clean() {
        cleanProxy();
        cleanTask();
    }

    public static void cleanProxy() {
        proxyInfoLocal.remove();
    }

    public static void cleanTask() {
        taskLocal.remove();
    }

}
